<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="body">
      <div class="project">
        <el-form
          :model="basicForm"
          label-position="top"
          :rules="basicRules"
          ref="basicFormRef"
        >
          <!-- 绛溪实验室信息 -->
          <div class="project-part">
            <div class="project-part-title">团队信息</div>

            <el-row>
              <el-col :span="6">
                <el-form-item
                  label="科研团队/中心名称"
                  prop="name"
                >
                  <el-input
                    v-model="basicForm.name"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="所属机构">
                  <el-select
                    v-model="basicForm.organizationId"
                    :disabled="isDetail"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="领域方向">
                  <!-- <el-select
                    v-model="basicForm.directWay"
                    :disabled="isDetail"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in scienceFieldOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select> -->
                  <el-input
                    v-model="basicForm.directWay"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="联系人及方式">
                  <el-input
                    v-model="basicForm.contract"
                    placeholder="如李某某，13800138000"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="团队负责人">
                  <el-input
                    v-model="basicForm.chiefScientist"
                    placeholder=""
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="团队负责人">
                  <el-input
                    v-model="basicForm.teamLeader"
                    placeholder=""
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="团队介绍">
                  <el-input
                    v-model="basicForm.introduce"
                    placeholder="请输入"
                    type="textarea"
                    :rows="3"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 科研成果 -->
          <div class="project-part">
            <div class="project-part-title">科研成果</div>

            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="科研项目数量">
                  <el-input
                    v-model="basicForm.projectCount"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <!-- <el-col :span="6">
                <el-form-item
                  label="科研项目名称"
                  style="width: 100%"
                >
                  <el-input
                    v-model="basicForm.projectName"
                    placeholder="科研项目名称 用，隔开或直接换行"
                    :disabled="isDetail"
                    type="textarea"
                    :rows="3"
                  ></el-input>
                </el-form-item>
              </el-col> -->

              <el-col :span="6">
                <el-form-item label="申报专利数量">
                  <el-input
                    v-model="basicForm.patentCount"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <!-- <el-col :span="6">
                <el-form-item
                  label="申报专利名称"
                  style="width: 100%"
                >
                  <el-input
                    v-model="basicForm.patentName"
                    placeholder="申报专利名称 用，隔开或直接换行"
                    :disabled="isDetail"
                    type="textarea"
                    :rows="3"
                  ></el-input>
                </el-form-item>
              </el-col> -->
              <el-col :span="6">
                <el-form-item label="可转化成果数量">
                  <el-input
                    v-model="basicForm.transformCount"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="可转化成果名称"
                  style="width: 100%"
                >
                  <el-input
                    v-model="basicForm.transformName"
                    placeholder="可转化成果名称 用，隔开或直接换行"
                    :disabled="isDetail"
                    type="textarea"
                    :rows="3"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="孵化企业数量">
                  <el-input
                    v-model="basicForm.hatchCount"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="孵化企业成果"
                  style="width: 100%"
                >
                  <el-input
                    v-model="basicForm.hatchName"
                    placeholder="孵化企业成果 用，隔开或直接换行"
                    :disabled="isDetail"
                    type="textarea"
                    :rows="3"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="科研平台数量">
                  <el-input
                    v-model="basicForm.platformCount"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="科研平台名称"
                  style="width: 100%"
                >
                  <el-input
                    v-model="basicForm.platformName"
                    placeholder="科研平台名称 用，隔开或直接换行"
                    :disabled="isDetail"
                    type="textarea"
                    :rows="3"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 图片上传 -->
          <div class="project-part">
            <div class="project-part-title">图片上传</div>
            <el-form-item label="">
              <el-upload
                class="upload-image"
                action=""
                list-type="picture-card"
                :auto-upload="false"
                :on-change="handleChangeImage"
                :on-remove="handleRemoveImage"
                :on-preview="handlePreviewImage"
                :show-file-list="true"
                :file-list="fileList"
                v-if="!isDetail"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"
                  ><div class="icon-text">上传图片</div></i
                >
                <div slot="tip" class="el-upload__tip">
                  支持格式：jpg、png，单个文件不能超过 5MB
                </div>
              </el-upload>

              <el-dialog
                :visible.sync="previewVisible"
                width="50%"
                v-if="!isDetail"
              >
                <img
                  :src="previewImage"
                  alt="预览"
                  style="width: 100%"
                />
              </el-dialog>
              <el-image
                v-for="item in fileList"
                :preview-src-list="previewImageList"
                v-if="isDetail"
                :key="item.url"
                :src="item.url"
                class="image"
              >
              </el-image>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import {
  addLaboratoryManagement,
  uploadFileById
} from '@/api/dataManagement'
import {
  scienceTypeOptions,
  scienceFieldOptions
} from '@/utils/project/data'
import { STATIC_FILE_URL } from '@/api/config.js'

export default {
  props: {
    pkid: String,
    title: String,
    data: Object,
    options: Array,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Breadcrumb
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        name: '',
        directWay: '',
        projectCount: '',
        projectName: '',
        patentCount: '',
        patentName: '',
        transformCount: '',
        transformName: '',
        receptResearchCount: '',
        researchContent: '',
        contract: '',
        picture: '',
        introduce: '',
        organizationId: '',
        chiefScientist: '',
        teamLeader: '',
        hatchCount: '',
        hatchName: '',
        platformCount: '',
        platformName: ''
      },
      basicRules: {
        name: [
          {
            required: true,
            message: '请输入科研中心名称',
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      props: { multiple: true },
      uploadFileList: [],
      previewImage: '',
      previewVisible: false,
      previewImageList: [],
      fileList: []
    }
  },
  computed: {
    titles() {
      return [this.title]
    },
    scienceTypeOptions() {
      return scienceTypeOptions
    },
    scienceFieldOptions() {
      return scienceFieldOptions
    }
  },
  watch: {},
  mounted() {
    if (this.pkid) {
      this.basicForm = JSON.parse(JSON.stringify(this.data))
      if (
        this.data.resourceFileInfos &&
        this.data.resourceFileInfos.length
      ) {
        this.fileList = this.data.resourceFileInfos.map(
          (item) => {
            return {
              ...item,
              url: `${STATIC_FILE_URL}${item.filePath}`
            }
          }
        )

        if (this.isDetail) {
          this.previewImageList = this.fileList.map(
            (item) => item.url
          )
        }

        this.uploadFileList = JSON.parse(
          JSON.stringify(this.fileList)
        )
      }
    }
  },
  methods: {
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJpgOrPng) {
        this.uploadFileList = this.uploadFileList.filter(
          (i) => i.name !== file.name
        )
        this.fileList = this.fileList.filter(
          (i) => i.name !== file.name
        )
        this.$message.error(
          '只能上传 JPG 或 PNG 格式的图片'
        )
        return
      }

      if (!isLt5M) {
        this.uploadFileList = this.uploadFileList.filter(
          (i) => i.name !== file.name
        )
        this.fileList = this.fileList.filter(
          (i) => i.name !== file.name
        )
        this.$message.error('图片大小不能超过 5MB')
        return
      }
    },
    handleRemoveImage(file) {
      file.name
        ? (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.name !== file.name
          ))
        : (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.url !== file.url
          ))
    },

    handleChangeImage(file) {
      this.uploadFileList.push(file.raw)
    },

    handlePreviewImage(file) {
      if (file.url) {
        this.previewImage = file.url
      } else if (file.raw) {
        this.previewImage = URL.createObjectURL(file.raw)
      }
      this.previewVisible = true
    },

    saveInfo() {
      this.$refs.basicFormRef.validate((res) => {
        if (res) {
          const currentUpload = this.uploadFileList.filter(
            (i) => !i.pkid
          )
          const isUploadImage = this.uploadFileList
            .filter((i) => i.pkid)
            .map((item) => item.pkid)

          const uploadPromises = currentUpload.map(
            (file) => {
              const image = new FormData()
              image.append('file', file)
              return uploadFileById(image)
            }
          )

          Promise.all(uploadPromises)
            .then((results) => {
              const allSuccess = results.every(
                (res) => res.success
              )

              if (!allSuccess) {
                this.$message.error('部分图片上传失败')
                return
              }

              let imageArr = results.map(
                (item) => item.data
              )
              this.basicForm.picture = imageArr
                .concat(isUploadImage)
                .join(',')

              // if (this.pkid) {
              //   this.basicForm.resourceFileInfos = null
              // }
              addLaboratoryManagement(this.basicForm).then(
                (res) => {
                  if (res.success) {
                    this.$message.success(
                      this.pkid ? '编辑成功' : '保存成功'
                    )
                    this.$router.push({
                      path: '/dataManagement/technologyManagement/laboratoryManagement/list',
                      query: { refresh: Date.now() }
                    })
                  } else {
                    this.$message.error(res.message)
                  }
                }
              )
            })
            .catch((err) => {
              this.loading = false
              this.$message.error('图片上传出错')
              console.error(err)
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .body {
    padding: 10px 0 0 20px;

    // &-left {
    //   width: 70%;
    //   border-right: 1px solid #f1f1f1;
    //   overflow: scroll;
    // }

    // &-right {
    //   flex: 1;
    //   padding-left: 10px;
    // }

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .line {
    display: flex;
    justify-content: center;
  }

  .el-icon-plus {
    margin-top: 50px;
    .icon-text {
      color: #999;
      font-size: 16px;
      margin-top: 10px;
    }
  }
}

::v-deep .el-upload-list__item-status-label {
  display: none !important;
}

.image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
}
</style>
